package com.cskaoyan.connectionpool;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * 创建日期: 2021/11/24 11:36
 *
 * @author ciggar
 * 自己实现的数据库连接池
 * 要实现两个功能
 *  1. 获取连接
 *  2. 返回连接
 *
 *  增加自动扩容的功能
 */
public class MyConnectionPool2 {

    // 从头部存，从尾部取
    static LinkedList<Connection> connectionList;

    static {

        connectionList = new LinkedList<>();

        for (int i = 0; i < 10; i++) {

            // 1. 获取连接
            Connection connection = JDBCUtils.getConnection();

            // 2. 把获取到的连接放到connectionList中
            connectionList.addFirst(connection);

        }
    }



    // 获取连接
    public static Connection getConnection(){

        if (connectionList.size() < 5){
            for (int i = 0; i < 5; i++) {
                // 1. 获取连接
                Connection connection = JDBCUtils.getConnection();

                // 2. 把获取到的连接放到connectionList中
                connectionList.addFirst(connection);
            }
        }

        Connection connection = connectionList.removeLast();
        return connection;

    }


    // 返回连接
    public static void returnConnection(Connection connection){

        connectionList.addFirst(connection);

    }

}
